<?php
$project_id = intval( dPgetParam( $_POST, 'project_id', 0 ) );
$item_type = intval( dPgetParam( $_POST, 'item_type', 0 ) );

$q = new DBQuery();
$q->dropTemp('itemdetails, pitems');
$q->exec();
$q->clear();


$q->createTemp('itemdetails');
$q->addTable('items');
$q->addQuery('items.*, t.name as type_name');
$q->innerJoin('md_type', 't', 't.type_id = items.item_type1');
if ($item_type > 0) {
	$q->addWhere("item_type1 = $item_type");
}
$q->exec();
$q->clear();

// reference
$q->addTable('projects');
$q->innerJoin('companies', 'c', 'company_id = project_company');
$q->leftJoin('project_items', 'pi', 'pitem_project = project_id');
$q->addWhere('project_id='.$project_id);
$q->addQuery('project_code, project_name, project_iso_code, company_code, company_name, pi.*');
$q->setLimit(1);
$project = $q->loadHash();

// taskLog
$q->addTable('tasks');
$q->leftJoin('task_log','tl','task_id = task_log_task');
$q->addQuery('task_name, sum(task_log_amount) as task_amount');
$q->addWhere('task_project='.$project_id);
$q->addGroup('task_id');
//echo $q->prepare();
$result = $q->loadList();
//echo'<pre>';print_r( $result);echo'</pre>'; exit;

include_once(DP_BASE_DIR."/modules/reports/xtpl/xtemplate.class.php");

$xtpl = new XTemplate(DP_BASE_DIR."/modules/reports/Settlement.xtpl");
$size = count($result);
// simple replace

// parse block1

for($i=0; $i<$size;$i++) {
	$xtpl->assign('DATA',$result[$i]);
	$xtpl->assign('no',$i+1);
	$xtpl->parse('main.row');
}

$xtpl->assign('REFERENCE_CODE', "[" .$project['project_code'] ."] " . $project['project_name']);
$xtpl->assign('REFERENCE_NUMBER', $project['project_iso_code']);
$xtpl->assign('CUSTOMER_CODE', $project['company_code']);
$xtpl->assign('CUSTOMER_NAME', $project['company_name']);

$xtpl->assign('INVOICE_NUMBER', $project['pitem_invoice_no']);
$xtpl->assign('BL_AW_NUMBER', $project['pitem_BL_AW']);
$xtpl->assign('DELIVERY_DATE', $project['pitem_delivery_date']);
$xtpl->assign('CUSTOMS_DECLARATION_NUMBER', $project['pitem_customs_dec_no']);
$xtpl->assign('EXR', $size+15);
$xtpl->assign('SIZE', $size);
$xtpl->parse('main');
$out = $xtpl->out('main');

$temp_dir = dPgetConfig( 'root_dir' )."/files/temp";
if ($fp = fopen( "$temp_dir/temp$AppUI->user_id.xls", 'wb' )) {
	fwrite( $fp, $out);
	fclose( $fp );
	header("Content-Type: application/vnd.ms-excel; charset=UTF-8");
	header("Content-Disposition: inline; filename=\"Settlement.xls\"");
	readfile("$temp_dir/temp$AppUI->user_id.xls");
}

?>
